package com.hnyfkj.jyindustry.biz.sysmemberinfo.sevice.Impl;

import java.time.LocalDateTime;
import java.util.Arrays;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hnyfkj.jyindustry.biz.admin.service.SysUserTokenService;
import com.hnyfkj.jyindustry.biz.login.dto.ChangePasswordDto;
import com.hnyfkj.jyindustry.biz.parameter.dao.ParameterDao;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.dao.SysMemberInfoDao;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.dto.SysMemberInfoDto;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.dto.SysMemberInfoInsertDto;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.dto.SysMemberInfoQueryDto;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.dto.SysMemberInfoUpdateDto;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.entity.SysMemberInfoEntity;
import com.hnyfkj.jyindustry.biz.sysmemberinfo.sevice.SysMemberInfoService;
import com.hnyfkj.jyindustry.common.exception.HnyfkjBusinessException;
import com.hnyfkj.jyindustry.common.utils.PageUtils;
import com.hnyfkj.jyindustry.common.utils.Response;
import com.hnyfkj.jyindustry.common.utils.ShiroUtils;

/**
 * @author zjq
 *
 * @Description
 *
 * @date 2020年12月10日
 */
@Service("sysMemberInfoService")
public class SysMemberInfoServiceImpl extends ServiceImpl<SysMemberInfoDao, SysMemberInfoEntity>
		implements SysMemberInfoService {

	private static Logger logger = LoggerFactory.getLogger(SysMemberInfoServiceImpl.class);

	@Autowired
	private SysMemberInfoDao sysMemberInfoDao;
	@Autowired
	private ParameterDao parameterDao;

	@Value("${effectTime}")
	private String effectTime;

	@Autowired
	private SysUserTokenService sysTokenService;

	@Override
	public int insert(final SysMemberInfoInsertDto sysMemberInfoDto) {
		final SysMemberInfoEntity sysMemberInfo = new SysMemberInfoEntity();
		BeanUtils.copyProperties(sysMemberInfoDto, sysMemberInfo);
		// 根据用户名查找
		SysMemberInfoEntity sys = new SysMemberInfoEntity();
		sys.setUserName(sysMemberInfo.getUserName());
		SysMemberInfoEntity one = sysMemberInfoDao.selectOne(new QueryWrapper<SysMemberInfoEntity>(sys));
		if (!StringUtils.isEmpty(one)) {
			throw new HnyfkjBusinessException("用户已存在");
		}
		return sysMemberInfoDao.insert(sysMemberInfo);
	}

	@Override
	public int update(SysMemberInfoUpdateDto updateDto) {
		if (logger.isDebugEnabled()) {
			logger.debug("{} select method param {}", SysMemberInfoServiceImpl.class.getSimpleName(),
					updateDto.toString());
		}
		// 验证手机号是否存在
		QueryWrapper<SysMemberInfoEntity> qw = new QueryWrapper<SysMemberInfoEntity>();
		qw.eq("phone", updateDto.getPhone());
		final SysMemberInfoEntity sysMember = sysMemberInfoDao.selectOne(qw);
		if (sysMember != null && !sysMember.getMemberId().equals(updateDto.getId())) {
			throw new HnyfkjBusinessException("手机号已存在");
		}
		final SysMemberInfoEntity sysMemberInfo = new SysMemberInfoEntity();
		sysMemberInfo.setEnterTime(LocalDateTime.now());
		sysMemberInfo.setMemberId(updateDto.getId());
		sysMemberInfo.setChargeArea(updateDto.getMemberArea());
		//sysMemberInfo.setMemberPic(updateDto.getMemberPic());
		sysMemberInfo.setName(updateDto.getRealName());
		return sysMemberInfoDao.updateById(sysMemberInfo);
	}

	@Override
	public PageUtils<SysMemberInfoDto> selectListDto(SysMemberInfoQueryDto queryDto) {
		if (queryDto != null && queryDto.getEnterTime() != null) {
			if (queryDto.getEnterTime().isEmpty()) {
				queryDto.setStartTime("");
				queryDto.setEndTime("");
			} else {
				queryDto.setStartTime(queryDto.getEnterTime().split(" - ")[0]);
				queryDto.setEndTime(queryDto.getEnterTime().split(" - ")[1]);
			}
		}
		PageHelper.startPage(queryDto.getPage(), queryDto.getLimit());
		PageInfo<SysMemberInfoDto> pageInfo = new PageInfo<>(sysMemberInfoDao.selectListDto(queryDto));
		pageInfo.setPageNum(queryDto.getPage());
		return PageUtils.pageOf(pageInfo);
	}

	@Override
	public int delectBatch(String[] memberIds) {
		return sysMemberInfoDao.deleteBatchIds(Arrays.asList(memberIds));
	}

	@Override
	public void logout(String token) {
		sysTokenService.delete(token);
	}

	@Override
	public SysMemberInfoEntity getByUserName(SysMemberInfoEntity sysMemberInfoEntity) {
		QueryWrapper<SysMemberInfoEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("user_name", sysMemberInfoEntity.getUserName());
		SysMemberInfoEntity one = this.getOne(wrapper);
		return one;
	}

	@Override
	public String passwordEncoder(String credentials, String salt) {
		Object object = new SimpleHash("MD5", credentials, salt, Integer.valueOf(effectTime));
		return object.toString();
	}

	@Override
	public Response changePassword(ChangePasswordDto changePasswordDto) {
		SysMemberInfoEntity one = this.getById((String) ShiroUtils.getSessionAttribute("memberId"));
		if (one == null) {
			throw new HnyfkjBusinessException("该用户不存在");
		}
		String oldPassword = changePasswordDto.getOldPassword();
		if (passwordEncoder(oldPassword, one.getSalt()).equals(one.getPassword())) {
			String newPassword = passwordEncoder(changePasswordDto.getNewPassword(), one.getSalt());
			one.setPassword(newPassword);
			this.updateById(one);
		} else {
			throw new HnyfkjBusinessException("输入原密码错误");
		}
		return Response.success();
	}

	@Override
	public Response<String> initPassword(String id) {
		SysMemberInfoEntity one = this.getById(id);
		String initPassword = parameterDao.getSysParameter("initPassword");
		String newPassword = passwordEncoder(initPassword, one.getSalt());
		one.setPassword(newPassword);
		this.updateById(one);
		return Response.success();
	}
}
